<template>
  <div class="industry-template">
    <div class="page-header">
      <h2>业态模板管理</h2>
      <a-space>
        <a-button type="primary" @click="createTemplate"> 新建模板 </a-button>
        <a-button @click="importTemplate">导入模板</a-button>
      </a-space>
    </div>

    <!-- 模板分类 -->
    <a-card title="模板分类" style="margin-bottom: 16px">
      <a-radio-group
        v-model:value="selectedCategory"
        @change="onCategoryChange"
      >
        <a-radio-button value="all">全部</a-radio-button>
        <a-radio-button value="hotel">酒店</a-radio-button>
        <a-radio-button value="pet">宠物</a-radio-button>
        <a-radio-button value="education">教育</a-radio-button>
        <a-radio-button value="retail">零售</a-radio-button>
        <a-radio-button value="manufacturing">制造</a-radio-button>
        <a-radio-button value="finance">金融</a-radio-button>
        <a-radio-button value="healthcare">医疗</a-radio-button>
      </a-radio-group>
    </a-card>

    <!-- 模板列表 -->
    <a-card title="模板列表">
      <a-table
        :columns="columns"
        :data-source="templates"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'industryType'">
            <a-tag :color="getIndustryColor(record.industryType)">
              {{ getIndustryLabel(record.industryType) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'usageCount'">
            <span>{{ record.usageCount }} 次</span>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a @click="viewTemplate(record)">查看</a>
              <a @click="editTemplate(record)">编辑</a>
              <a @click="copyTemplate(record)">复制</a>
              <a @click="exportTemplate(record)">导出</a>
              <a-popconfirm
                title="确定要删除这个模板吗？"
                @confirm="deleteTemplate(record.id)"
              >
                <a class="text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新建/编辑模板模态框 -->
    <a-modal
      v-model:open="templateModalVisible"
      :title="isEdit ? '编辑模板' : '新建模板'"
      width="800px"
      @ok="handleTemplateSubmit"
      @cancel="handleTemplateCancel"
    >
      <a-form
        ref="templateFormRef"
        :model="templateForm"
        :rules="templateRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="模板名称" name="name">
              <a-input
                v-model:value="templateForm.name"
                placeholder="请输入模板名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="模板编码" name="code">
              <a-input
                v-model:value="templateForm.code"
                placeholder="请输入模板编码"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="业态类型" name="industryType">
          <a-select
            v-model:value="templateForm.industryType"
            placeholder="请选择业态类型"
          >
            <a-select-option value="hotel">酒店</a-select-option>
            <a-select-option value="pet">宠物</a-select-option>
            <a-select-option value="education">教育</a-select-option>
            <a-select-option value="retail">零售</a-select-option>
            <a-select-option value="manufacturing">制造</a-select-option>
            <a-select-option value="finance">金融</a-select-option>
            <a-select-option value="healthcare">医疗</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="模板描述" name="description">
          <a-textarea
            v-model:value="templateForm.description"
            placeholder="请输入模板描述"
            :rows="3"
          />
        </a-form-item>
        <a-form-item label="模板配置" name="config">
          <a-textarea
            v-model:value="templateForm.config"
            placeholder="请输入模板配置（JSON格式）"
            :rows="8"
          />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="templateForm.status">
            <a-radio value="active">启用</a-radio>
            <a-radio value="inactive">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';

// 响应式数据
const loading = ref(false);
const selectedCategory = ref('all');
const templateModalVisible = ref(false);
const isEdit = ref(false);
const templateFormRef = ref<FormInstance>();

const templates = ref<any[]>([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
});

const templateForm = reactive({
  id: '',
  name: '',
  code: '',
  industryType: '',
  description: '',
  config: '',
  status: 'active',
});

const templateRules = {
  name: [{ required: true, message: '请输入模板名称' }],
  code: [{ required: true, message: '请输入模板编码' }],
  industryType: [{ required: true, message: '请选择业态类型' }],
  description: [{ required: true, message: '请输入模板描述' }],
  config: [{ required: true, message: '请输入模板配置' }],
};

// 表格列配置
const columns = [
  { title: '模板名称', dataIndex: 'name', key: 'name', width: 200 },
  { title: '模板编码', dataIndex: 'code', key: 'code', width: 150 },
  {
    title: '业态类型',
    dataIndex: 'industryType',
    key: 'industryType',
    width: 120,
  },
  { title: '描述', dataIndex: 'description', key: 'description', width: 300 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '使用次数', dataIndex: 'usageCount', key: 'usageCount', width: 100 },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
  { title: '操作', key: 'action', width: 200, fixed: 'right' },
];

// 工具函数
const getIndustryColor = (type: string) => {
  const colors: Record<string, string> = {
    hotel: 'blue',
    pet: 'green',
    education: 'orange',
    retail: 'purple',
    manufacturing: 'cyan',
    finance: 'gold',
    healthcare: 'red',
  };
  return colors[type] || 'default';
};

const getIndustryLabel = (type: string) => {
  const labels: Record<string, string> = {
    hotel: '酒店',
    pet: '宠物',
    education: '教育',
    retail: '零售',
    manufacturing: '制造',
    finance: '金融',
    healthcare: '医疗',
  };
  return labels[type] || type;
};

const getStatusColor = (status: string) => {
  return status === 'active' ? 'green' : 'red';statusstatus
};

const getStatusLabel = (status: string) => {
  return status === 'active' ? '启用' : '禁用';statusstatus
};

// 事件处理
const onCategoryChange = () => {
  pagination.current = 1;
  loadTemplates();
};

const createTemplate = () => {
  isEdit.value = false;
  resetTemplateForm();
  templateModalVisible.value = true;
};

const editTemplate = (record: any) => {
  isEdit.value = true;
  Object.assign(templateForm, record);
  templateModalVisible.value = true;
};

const viewTemplate = (record: any) => {
  message.info(`查看模板: ${record.name}`);
};

const copyTemplate = (record: any) => {
  message.info(`复制模板: ${record.name}`);
};

const exportTemplate = (record: any) => {
  message.info(`导出模板: ${record.name}`);
};

const importTemplate = () => {
  message.info('导入模板功能');
};

const deleteTemplate = async (id: string) => {
  try {
    message.success('删除成功');
    await loadTemplates();
  } catch (error) {
    message.error('删除失败');
  }
};

const handleTemplateSubmit = async () => {
  try {
    await templateFormRef.value?.validate();
    message.success(isEdit.value ? '编辑成功' : '创建成功');
    templateModalVisible.value = false;
    await loadTemplates();
  } catch (error) {
    message.error('操作失败');
  }
};

const handleTemplateCancel = () => {
  templateModalVisible.value = false;
  resetTemplateForm();
};

const resetTemplateForm = () => {
  Object.assign(templateForm, {
    id: '',
    name: '',
    code: '',
    industryType: '',
    description: '',
    config: '',
    status: 'active',
  });
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadTemplates();
};

// 加载模板数据
const loadTemplates = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        id: '1',
        name: '酒店管理系统模板',
        code: 'HOTEL_MANAGEMENT',
        industryType: 'hotel',
        description: '适用于酒店行业的完整管理系统模板',
        status: 'active',
        usageCount: 15,
        createTime: '2024-01-15 10:30:00',
        config: JSON.stringify(
          {
            modules: ['booking', 'room', 'customer', 'finance'],
            features: ['online_booking', 'room_management', 'customer_service'],
          },
          null,
          2,
        ),
      },
      {
        id: '2',
        name: '宠物医院管理系统',
        code: 'PET_HOSPITAL',
        industryType: 'pet',
        description: '专为宠物医院设计的业务管理系统',
        status: 'active',
        usageCount: 8,
        createTime: '2024-01-10 14:20:00',
        config: JSON.stringify(
          {
            modules: ['appointment', 'medical', 'inventory', 'billing'],
            features: [
              'appointment_scheduling',
              'medical_records',
              'inventory_management',
            ],
          },
          null,
          2,
        ),
      },
      {
        id: '3',
        name: '在线教育平台',
        code: 'EDU_PLATFORM',
        industryType: 'education',
        description: '在线教育机构管理系统模板',
        status: 'inactive',
        usageCount: 3,
        createTime: '2024-01-05 09:15:00',
        config: JSON.stringify(
          {
            modules: ['course', 'student', 'teacher', 'assessment'],
            features: [
              'course_management',
              'student_tracking',
              'online_assessment',
            ],
          },
          null,
          2,
        ),
      },
    ];

    // 根据分类过滤
    let filteredData = mockData;
    if (selectedCategory.value !== 'all') {
      filteredData = mockData.filter(
        (item) => item.industryType === selectedCategory.value,
      );
    }

    templates.value = filteredData;
    pagination.total = filteredData.length;
  } catch (error) {
    message.error('加载模板失败');
  } finally {
    loading.value = false;
  }
};

// 生命周期
onMounted(() => {
  loadTemplates();
});
</script>

<style lang="less" scoped>
.industry-template {
  padding: 24px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h2 {
      margin: 0;
    }
  }

  .text-danger {
    color: #ff4d4f;
  }
}
</style>
